package com.scalar.chiptrack.finance.openpo.actioncommands;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;

import javax.mail.internet.InternetAddress;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.ScalarException;
import com.scalar.chiptrack.actioncommands.ActionCommand;
import com.scalar.chiptrack.commons.Address;
import com.scalar.chiptrack.commons.ClientInfo;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.finance.openpo.dao.PurchaseOrderDAO;
import com.scalar.chiptrack.finance.openpo.forms.OpenPurchaseOrderForm;
import com.scalar.chiptrack.finance.openpo.forms.PurchaseOrderForm;
import com.scalar.chiptrack.finance.openpo.forms.PurchaseOrderReceiptForm;
import com.scalar.chiptrack.operations.vendor.Vendor;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;
import com.scalar.chiptrack.sales.forms.SendAckMailForm;
import com.scalar.chiptrack.users.ErrorReport;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.dao.UserDAO;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.Mailer;
import com.scalar.chiptrack.utils.PDFGenerator;
import com.scalar.chiptrack.utils.StringUtils;

/**
 * User: Murali Krishna Yengala
 * Date: Feb 21, 2005
 * Time: 4:43:18 PM
 */
public class OpenPurchaseOrderSendMailCommand extends ActionCommand{
    /*
	 * To load Open Purchase Order for Priter Friendly Version
	 */
	public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		HashMap errors			= ( HashMap ) request.getAttribute( ERROR_MESSAGES );
		HashMap info            = ( HashMap ) request.getAttribute( INFO_MESSAGES );
        String action   		= request.getParameter( REQUEST_ACTION );
		String actionForward 	= "sendMail";
        String poTypeAsString   = request.getParameter( "poType" ) ;
        String vendorId         = request.getParameter( "vendorId" ) ;
        int vendor_id           = Integer.parseInt( vendorId );
        int    poType           = Integer.parseInt( poTypeAsString );

        HttpSession mSession 	= request.getSession();

        try
        {
            if( action.equalsIgnoreCase( "sendMail" ) )
            {
                String purchaseOrderId                              = request.getParameter( "purchaseOrderId");
                OpenPurchaseOrderForm purchaseOrderForm             = new OpenPurchaseOrderForm();
                PurchaseOrderForm standardpurchaseOrderForm         = new PurchaseOrderForm();
                PurchaseOrderReceiptForm purchaseOrderReceiptForm   = new PurchaseOrderReceiptForm();

                if ( purchaseOrderId != null )
                {
                    if( ( poType != -1 )&&( poType == 1 ) )
                    {
                        purchaseOrderForm.setPurchaseOrder_id( Integer.parseInt(purchaseOrderId) );
                        PurchaseOrderDAO.loadOpenPurchaseOrder( purchaseOrderForm );
                        ClientInfo clientInfo = UserDAO.getClientAddressInfo();
                        purchaseOrderForm.setClientInfo( clientInfo);
                        purchaseOrderForm.setBillingAddress( PurchaseOrderDAO.getClientAddress() );
                        purchaseOrderForm.setShippingAddress( PurchaseOrderDAO.getAddress( purchaseOrderForm.getShippingAddress_id() ) );
                    }
                    else if( ( ( poType != -1 )&&( poType == 2 ) ) || ( ( poType != -1 )&&( poType == 3 ) )  )
                    {
                        ClientInfo clientInfo = UserDAO.getClientAddressInfo();
                        standardpurchaseOrderForm.setClientInfo( clientInfo);
                        standardpurchaseOrderForm.setPurchaseOrder_Id( Integer.parseInt(purchaseOrderId) );
                        Vendor vendor = VendorDAO.getVendorDetails( vendor_id );
                        standardpurchaseOrderForm.setVendorName( vendor.getVendorName() );

                        try
                        {
                            PurchaseOrderDAO.loadPurchaseOrder( standardpurchaseOrderForm) ;

                            standardpurchaseOrderForm.setBillingAddress( PurchaseOrderDAO.getClientAddress() );
                            standardpurchaseOrderForm.setShippingAddress( PurchaseOrderDAO.getAddress( standardpurchaseOrderForm.getShippingAddress_id() ) );
                        }
                        catch( ScalarException se)
                        {
                            Logger.error( ERROR_LOADING_PURCHASE_ORDER_INFORMATION, se );
                            errors.put( ERROR_INTERNAL_SERVER_ERROR, ERROR_LOADING_PURCHASE_ORDER_INFORMATION );
                            se.printStackTrace();
                        }
                    }
                    else if ( ( poType != -1 )&&( poType == 4 ) )
                    {
                        try
                        {
                            String receiptId = request.getParameter( "receiptId" );
                            purchaseOrderReceiptForm.setReceipt_id( Integer.parseInt( receiptId) );
                        }
                        catch( Exception e)
                        {
                            purchaseOrderReceiptForm.setReceipt_id(0);
                        }
                        try{
                            PurchaseOrderDAO.loadPurchaseOrderReceipt( purchaseOrderReceiptForm ) ;
                            ClientInfo clientInfo = UserDAO.getClientAddressInfo();
                            purchaseOrderReceiptForm.setClientInfo( clientInfo);

                            Vendor vendor          = VendorDAO.getVendorDetails( vendor_id );
                            purchaseOrderReceiptForm.setVendorName( vendor.getVendorName() );
                        }
                        catch( ScalarException se)
                        {
                            se.printStackTrace();
                        }

                    }

                    SendAckMailForm sendAckMailForm = ( SendAckMailForm ) form;
                    String from = null;
                    String subject = null;
                    User user = ( User ) mSession.getAttribute ( SessionKeys.USER_KEY );
                    String mimeType = sendAckMailForm.getAttachMIMEType ();

                    if ( ( mimeType == null ) || ( mimeType.trim ().length () == 0 ) )
                    {
                        mimeType = "PDF";
                        sendAckMailForm.setAttachMIMEType ( "PDF" );
                    }
                    from = user.getEmail();
                    try
                    {
                        String to = StringUtils.concatStrings ( sendAckMailForm.getToUsers (), Mailer.EMAIL_SEPARATOR );
                        String cc = StringUtils.concatStrings ( sendAckMailForm.getCcUsers (), Mailer.EMAIL_SEPARATOR );
                        String bcc = StringUtils.concatStrings ( sendAckMailForm.getBccUsers (), Mailer.EMAIL_SEPARATOR );

                        to = Mailer.getNotifiableEmails ( to, false );
                        cc = Mailer.getNotifiableEmails ( cc, false );
                        bcc = Mailer.getNotifiableEmails ( bcc, false );

                        if ( cc == null )
                        {
                            sendAckMailForm.setCcUsers ( null );
                        }
                        if ( bcc == null )
                        {
                            sendAckMailForm.setBccUsers ( null );
                        }

                        subject = sendAckMailForm.getSubject ();

                        if ( subject == null )
                        {
                            if( ( poType != -1 )&&( poType == 1 ) )
                            {
                                subject = "Open Purchase Order Acknowledgement for "+purchaseOrderForm.getPoNumber();
                            }
                            else if( ( poType != -1 )&&( poType == 2 ) )
                            {
                                subject = "Standard Purchase Order Acknowledgement for "+standardpurchaseOrderForm.getPurchaseOrderNumber();
                            }
                            else if( ( poType != -1 )&&( poType == 3 ) )
                            {
                                subject = "DropShip Purchase Order Acknowledgement for "+standardpurchaseOrderForm.getPurchaseOrderNumber();
                            }
                            else
                            {
                                subject = "Purchase Order Receipt Acknowledgement for "+purchaseOrderReceiptForm.getPurchaseOrderNumber();
                            }

                        }
                        sendAckMailForm.setSubject ( subject );

                        String message = sendAckMailForm.getMessage ();
                        if ( from != null )
                        {
                            sendAckMailForm.setFromUser( from );
                        }
                        String host = request.getHeader ( "HOST" );
                        String salesAckFile = null;

                        if ( "PDF".equalsIgnoreCase ( mimeType ) )
                        {
                            if( ( poType != -1 )&&( poType == 1 ) )
                            {
                                salesAckFile = getSalesAckPDFFile ( purchaseOrderForm );
                            }
                            else if( ( poType != -1 )&&( ( poType == 2 )||( poType == 3 ) ) )
                            {
                                salesAckFile = PurchaseOrderForm.getPurchaseOrderAsPDFFile( standardpurchaseOrderForm );

                            }
                            else if( ( poType != -1 )&&( poType == 4 ) )
                            {
                                salesAckFile = PurchaseOrderReceiptForm.getPurchaseOrderAsPDFFile( purchaseOrderReceiptForm );

                            }
                        }
                        else
                        {
                            if( ( poType != -1 )&&( poType == 1 ) )
                            {
                                salesAckFile = getsalesAckHtmlFile ( host, purchaseOrderForm );
                            }
                            else if( ( poType != -1 )&&( ( poType == 2 )||( poType == 3 ) ) )
                            {
                                salesAckFile = standardpurchaseOrderForm.getPurchaseOrderAckHtmlFile( host, standardpurchaseOrderForm );
                            }
                            else if( ( poType != -1 )&&(  poType == 4 )  )
                            {
                                salesAckFile = purchaseOrderReceiptForm.getPurchaseOrderAckHtmlFile( host, purchaseOrderReceiptForm );
                            }
                        }

                        String[] mailAttachments = null;

                        String isConfirm = ( String ) mSession.getAttribute ( "isConfirm" );
                        String sysAdminEmail = ConfigManager.getSysAdminEmail ();
                        String companyEmailId = sysAdminEmail.substring ( sysAdminEmail.indexOf ( "@" ) + 1, sysAdminEmail.length () );
                        if ( isConfirm == null )
                        {

                            to = Mailer.getNotifiableEmails ( to, false );
                            cc = Mailer.getNotifiableEmails ( cc, false );
                            bcc = Mailer.getNotifiableEmails ( bcc, false );
                            InternetAddress[] toAddress = null;
                            InternetAddress[] ccAddress = null;
                            InternetAddress[] bccAddress = null;
                            String emailIds = "";
                            if ( to != null )
                            {
                                toAddress = InternetAddress.parse ( to );
                                for ( int i = 0; i < toAddress.length; i++ )
                                {
                                    InternetAddress temp = toAddress[i];
                                    String address = temp.getAddress ();
                                    if ( address.indexOf ( companyEmailId ) == -1 )
                                    {
                                        if(emailIds == "" )
                                        {
                                            emailIds = emailIds + temp.getAddress () ;
                                        }
                                        else
                                        {
                                            emailIds = emailIds +", "+ temp.getAddress () ;
                                        }
                                    }
                                }
                            }
                            if ( cc != null )
                            {
                                ccAddress = InternetAddress.parse ( cc );
                                for ( int i = 0; i < ccAddress.length; i++ )
                                {
                                    InternetAddress temp = ccAddress[i];
                                    String address = temp.getAddress ();
                                    if ( address.indexOf ( companyEmailId ) == -1 )
                                    {
                                        if(emailIds == "" )
                                        {
                                            emailIds = emailIds + temp.getAddress () ;
                                        }
                                        else
                                        {
                                            emailIds = emailIds +", "+ temp.getAddress () ;
                                        }

                                    }
                                }
                            }
                            if ( bcc != null )
                            {
                                bccAddress = InternetAddress.parse ( bcc );
                                for ( int i = 0; i < bccAddress.length; i++ )
                                {
                                    InternetAddress temp = bccAddress[i];
                                    String address = temp.getAddress ();
                                    if ( address.indexOf ( companyEmailId ) == -1 )
                                    {
                                        if(emailIds == "" )
                                        {
                                            emailIds = emailIds + temp.getAddress () ;
                                        }
                                        else
                                        {
                                            emailIds = emailIds +", "+ temp.getAddress () ;
                                        }
                                    }
                                }
                            }
                            if ( emailIds.trim ().length () > 0 )
                            {
                                errors.put ( "The following e-mails are going out of the company. Please confirm to send them.", null );
                                info.put ( "Emails ", emailIds );
                                request.setAttribute ( "sendAckMailForm", sendAckMailForm );
                                mSession.setAttribute ( "isConfirm", "True" );
                                actionForward = "showSendMailWindow";
                                return mapping.findForward ( "showSendMailWindow" );
                            }

                        }
                        mailAttachments = new String[]{salesAckFile};
                        Mailer.send ( from, to, cc, bcc, subject, message, mailAttachments, Mailer.CONTENT_TYPE_HTML, false );
                        info.put ( "Email has been sent successfully", null );
                        mSession.removeAttribute ( "ShowAgain" );
                        mSession.removeAttribute ( "isConfirm" );
                    }
                    catch ( Exception se )
                    {
                        String errMessage = "Error";
                        errors.put ( errMessage, "Could not send Email. Please check the EmailId" );
                        se.printStackTrace ();
                        return mapping.findForward ( "showSendMailWindow" );
                    }
                    request.setAttribute ( "sendAckMailForm", sendAckMailForm );
                    return ( mapping.findForward ( "sendAckMailView" ) );
                }
                else
                {
                    //handler
                }
            }
        }
        catch ( Exception e )
        {
            e.printStackTrace();
            Logger.error( ERROR_LOADING_OPEN_PURCHASE_ORDER_INFORMATION, e );
            errors.put( ERROR_INTERNAL_SERVER_ERROR, ERROR_LOADING_OPEN_PURCHASE_ORDER_INFORMATION );
            mSession.setAttribute( ERROR_REPORT_OBJECT, new ErrorReport( "Error while executing the command", e ) );
            actionForward = "saveSuccess";
        }

        request.setAttribute( ERROR_MESSAGES, errors );
        request.setAttribute( INFO_MESSAGES, info );
        return mapping.findForward( actionForward );
    }

    public static String getSalesAckPDFFile (OpenPurchaseOrderForm purchaseOrderForm )
    {
        String fileXMLPath = null;
        String filePDFPath = null;

        String saAsXML = formatAsXML ( purchaseOrderForm );

        if ( saAsXML == null )
        {
            return fileXMLPath;
        }

        FileWriter fWriter = null;
        File saPDFAttachment = null;
        File saXML = null;

        try
        {
            String mailingTempDir = ConfigManager.getMailerTempDir ();
            File tempDir = new File ( mailingTempDir ).getCanonicalFile ();
            tempDir.mkdir ();


            String xmlFileName = "po_Ack_" + purchaseOrderForm.getPoNumber() + ".xml";
            String saAttachmentPDFFileName = "OpenPurchaseOrder_Ack_" + purchaseOrderForm.getPoNumber() + ".pdf";

            String xsltFileName = ConfigManager.getOpenPurchaseOrderAckXml2PdfXslFile();

            saXML = new File ( tempDir.getCanonicalPath (), xmlFileName );
            saXML.deleteOnExit ();

            saPDFAttachment = new File ( tempDir.getCanonicalPath (), saAttachmentPDFFileName );
            saPDFAttachment.deleteOnExit ();

            if ( ( saXML.exists () == true ) || ( saXML.createNewFile () == true ) )
            {
                fWriter = new FileWriter ( saXML, false );
                fWriter.write ( saAsXML );
                fWriter.close ();
                fWriter = null;

                fileXMLPath = saXML.getCanonicalPath ().toLowerCase ();
                filePDFPath = saPDFAttachment.getCanonicalPath ().toLowerCase ();

                boolean success = PDFGenerator.convertXML2PDF ( fileXMLPath, xsltFileName, filePDFPath );

            }
        }
        catch ( Exception e )
        {
            System.out.println ( "Exception while creating open Order Ack PDF file" );
            e.printStackTrace ();
        }
        finally
        {
            if ( fWriter != null )
            {
                try
                {
                    fWriter.close ();
                    fWriter = null;
                }
                catch ( IOException ignore )
                {
                }
            }
        }

        return filePDFPath;
    }

    public static String formatAsXML ( OpenPurchaseOrderForm opof )
    {
		StringBuffer buf 			= new StringBuffer ( 2098 );
		String imagesDirLocation 	= ConfigManager.getChipTracImagesDir();
		String scalarLogo 			= ConfigManager.getScalarLogo();
		String crossCancel 			= ConfigManager.getCrossCanelImage();

		buf.append ( "<?xml version='1.0' encoding='UTF-8'?>\n" );

        buf.append ( "<OpenPurchaseOrder> \n" );

		buf.append ( "<images>\n" );
		buf.append ( "<logo>"+imagesDirLocation + scalarLogo +"</logo> \n" );
		buf.append ( "<cancelImage>"+imagesDirLocation+crossCancel+"</cancelImage> \n" );
		buf.append ( "</images>\n" );
        Address clientAddress = opof.getClientInfo().getAddress();
        buf.append("<selfAddress>");
		buf.append ( "<name><![CDATA[" ) .append( opof.getClientInfo().getClientName() ) .append( "]]></name> \n" );
        buf.append ( "<address1><![CDATA[" + clientAddress.getAddress1 () + "]]></address1>" + "\n" );
        buf.append ( "<address2><![CDATA[" + clientAddress.getAddress2 () + "]]></address2>" + "\n" );
        buf.append ( "<address3><![CDATA[" + clientAddress.getAddress3 () + "]]></address3>" + "\n" );
        buf.append ( "<address4><![CDATA[" + clientAddress.getAddress4 () + "]]></address4>" + "\n" );
        StringBuffer cityStateZip = new StringBuffer ( "" );
        if ( !clientAddress.getCity ().equals ( "" ) ) cityStateZip.append ( clientAddress.getCity () + ", " );
        if ( !clientAddress.getState ().equals ( "" ) ) cityStateZip.append ( clientAddress.getState () + " - " );
        if ( !clientAddress.getZipCode ().equals ( "" ) ) cityStateZip.append ( clientAddress.getZipCode () + ", " );
        cityStateZip.append ( clientAddress.getCountry () );
        buf.append ( "<cityStateZip><![CDATA[" + cityStateZip + "]]></cityStateZip>" + "\n" );
        StringBuffer phFax = new StringBuffer ();
        if ( !clientAddress.getPhoneNumber ().equals ( "" ) ) phFax.append ( "Tel:" + clientAddress.getPhoneNumber () + ", " );
        if ( !clientAddress.getFaxNumber ().equals ( "" ) ) phFax.append ( "Fax:" + clientAddress.getFaxNumber () );
        buf.append ( "<phoneFax><![CDATA[" + phFax + "]]></phoneFax>" + "\n" );
        buf.append("</selfAddress>");

		buf.append ("").append( opof.formatAddressAsStringForXML( opof.getBillingAddress(), "billingAddress")).append("\n" );
		buf.append ("").append( opof.formatAddressAsStringForXML( opof.getShippingAddress(), "shippingAddress")).append("\n" );


		buf.append ( "<information> \n" );
		buf.append ( "<PONumber><![CDATA[" ) .append ( (opof.getPoNumber() == null) ? "" : opof.getPoNumber()) .append ( "]]></PONumber> \n" );
		buf.append ( "<POType><![CDATA[" ) .append ( (opof.getPOTypeString() == null) ? "" : opof.getPOTypeString()) .append ("]]></POType> \n");
		buf.append ( "<PODate><![CDATA[" ) .append ( (opof.getPoDate()== null) ? "" : opof.getPoDate()) .append ("]]></PODate> \n");
		buf.append ( "<VendorName><![CDATA[" ) .append( (opof.getVendorName()== null) ? "" : opof.getVendorName()) . append ( "]]></VendorName> \n" );
		buf.append ( "<VendorQuoteNo><![CDATA[" ) .append( (opof.getVendorQuoteNumber()== null) ? "" : opof.getVendorQuoteNumber()) . append ( "]]></VendorQuoteNo> \n" );
		buf.append ( "<POMax><![CDATA[" ) .append ( (opof.getPoMaxAmt()== null) ? "" : opof.getPoMaxAmt()) .append( "]]></POMax> \n" );
        buf.append ( "<ValidFrom><![CDATA[" ) .append ( (opof.getValidFromDate()== null) ? "" : opof.getValidFromDate()) .append( "]]></ValidFrom> \n" );
        buf.append ( "<ValidTo><![CDATA[" ) .append ( (opof.getValidToDate()== null) ? "" : opof.getValidToDate()) .append( "]]></ValidTo> \n" );
        buf.append ( "<shipMethod><![CDATA[" ) .append ( (opof.getShipMethod()== null) ? "" : opof.getShipMethod()) .append( "]]></shipMethod> \n" );
        buf.append ( "<payTerms><![CDATA[" ) .append ( (opof.getPayTerms()== null) ? "" : opof.getPayTerms()) .append( "]]></payTerms> \n" );
        buf.append ( "</information> \n" );

		buf.append ( "<Comments><![CDATA[" );
		buf.append ( ( ( opof.getComments()== null ) ? "" : opof.getComments().trim() ) );
		buf.append ( "]]></Comments> \n" );
		buf.append ( "</OpenPurchaseOrder>\n" );
		return buf.toString();
    }

    public static String  getsalesAckHtmlFile( String host, OpenPurchaseOrderForm purchaseOrderForm )
    {
        String filePath = null;

        String psAsHtml = formatAsHTML ( host, purchaseOrderForm );

        if ( psAsHtml == null )
        {
            return filePath;
        }

        FileWriter fWriter = null;
        File psAttachment = null;

        try
        {
            // CREATE TEMPORARY ATTACHMENT FILE
            String mailingTempDir = ConfigManager.getMailerTempDir ();
            File tempDir = new File ( mailingTempDir ).getCanonicalFile ();
            tempDir.mkdir ();
            String salesAttachmentFileName = null;
            salesAttachmentFileName = "OpenPurchaseOrder_Ack_" + purchaseOrderForm.getPoNumber() + ".html";
            psAttachment = new File ( tempDir.getCanonicalPath (), salesAttachmentFileName );
            psAttachment.deleteOnExit ();

            if ( ( psAttachment.exists () == true ) || ( psAttachment.createNewFile () == true ) )
            {
                fWriter = new FileWriter ( psAttachment, false );

                fWriter.write ( psAsHtml );

                fWriter.close ();
                fWriter = null;

                filePath = psAttachment.getAbsolutePath ();
            }
        }
        catch ( Exception e )
        {
            System.out.println ( "Exception while creating Sales Order Ack html file" );
            e.printStackTrace ();
        }
        finally
        {
            if ( fWriter != null )
            {
                try
                {
                    fWriter.close ();
                    fWriter = null;
                }
                catch ( IOException ignore )
                {
                }
            }
        }

        return filePath;
    }

    public static String formatAsHTML ( String host,OpenPurchaseOrderForm purchaseOrderForm )
    {
        StringBuffer buf = new StringBuffer ( 2098 );
        buf.append("<html lang='en'><HTML><HEAD><TITLE>Scalarsoft - ChipTrac</TITLE>");
        buf.append("<META http-equiv=Content-Type content='text/html; charset=windows-1252'>");
        buf.append("<style type='text/css'>a { text-decoration : none}@page {  size: landscape;</style>");
        buf.append("<LINK href='http://" + host + "/"+ ConfigManager.getChipTracContext ()  +"/jsp/includes/stylesheets/scalarsoft.css' type='text/css' rel='stylesheet'>");
        buf.append("</HEAD><BODY bgColor='#ffffff' leftMargin='0' topMargin='0' marginheight='0' marginwidth='0'>");
        buf.append("<form><table width='90%' align='center'><tr><td width='30%' align='left' valign='top'>");
        buf.append("<img src='http://" + host + "/"+ ConfigManager.getChipTracContext ()  +"/jsp/includes/images/scalar_logo.jpg' height='84' width='200' border='0'></td>");
		buf.append("<td width='40%'  align='center' class='NArialL'><font class='NArialW'>Open Purchase Order Acknowledgement</font><br>");
        buf.append( purchaseOrderForm.getClientInfo().getClientName());
        buf.append("<br>");
        buf.append( purchaseOrderForm.getClientAddressAsStringForHTML());
        buf.append("</td>");
        buf.append("<td width='15%'>");
        buf.append("</td>");
        buf.append("<td width='15%'></td></tr><tr><td height='35' colspan='4'>&nbsp;</td></tr><tr><td colspan='4' width='40%'><table width='100%' border='0' cellspacing='0' cellpadding='0'>");
		buf.append("<tr><td bgcolor='#FFFFEE'  height='100%' class='NArialRS' align='left' width='40%'>");
        buf.append("<table width='100%' height='100%' class='NArialRS' border='1' bordercolor='#000000' cellspacing='0'>");
        buf.append("<tr height=30><td class='NArialR' bgcolor='#DEE1E2' >Bill To Address:</td></tr><tr><td class='NArialRS' valign='top'>");
        buf.append( purchaseOrderForm.getBillingAddressAsStringForHTMLWithBreaks());
        buf.append("&nbsp;</td></tr></table></td>");
        buf.append("<td width='20%'><img src='http://" + host + "/"+ ConfigManager.getChipTracContext ()  +"/jsp/includes/images/spacer.gif'></td>");
        buf.append("<td bgcolor='#FFFFEE' class='NArialRS' align ='right'  width='40%' height='100%'><table width='100%'  height='100%' class='NArialRS' border='1' bordercolor='#000000' cellspacing='0'>");
        buf.append("<tr height=30><td class='NArialR' bgcolor='#DEE1E2' > Ship To Address:</td></tr><tr><td class='NArialRS' valign='top'>");
        buf.append(purchaseOrderForm.getShippingAddressAsStringForHTMLWithBreaks());
        buf.append("&nbsp;</td></tr></table></td></tr></table></td></tr>");

        buf.append("<tr><td colspan='4'><img src='http://" + host + "/"+ ConfigManager.getChipTracContext ()  +"/jsp/includes/images/spacer.gif' height=20></td></tr>");
        buf.append("<tr><td colspan=4><img src='http://" + host + "/"+ ConfigManager.getChipTracContext ()  +"/includes/images/spacer.gif' height=10></td></tr>");
        buf.append("<tr><td colspan=4 width='100%'><table border='1' width='100%' class='NArialRS' bordercolor='#000000' cellspacing='0'><tr>");
        buf.append("<td width='12%' align='center' bgcolor='#DEE1E2' class='NArialR'>PO Number</td>");
        buf.append("<td width='12%' align='center' bgcolor='#DEE1E2' class='NArialR'>PO Type</td>");
        buf.append("<td width='12%' align='center' bgcolor='#DEE1E2' class='NArialR'>PO Date</td>");
        buf.append("<td width='12%' align='center' bgcolor='#DEE1E2' class='NArialR'>Vendor Name</td>");
        buf.append("<td width='12%' align='center' bgcolor='#DEE1E2' class='NArialR'>Vendor Quote No</td>");
        buf.append("<td width='12%' align='center' bgcolor='#DEE1E2' class='NArialR'>PO Max $</td>");
        buf.append("<td width='14%'  align='center' bgcolor='#DEE1E2' class='NArialR'>Valid From</td>");
        buf.append("<td width='14%' align='center' bgcolor='#DEE1E2' class='NArialR'>Valid To</td>");
        buf.append("</tr><tr>");
        buf.append("<td width='12%' align='center' bgcolor='#FFFFEE'>");
        buf.append( purchaseOrderForm.getPoNumber());
        buf.append("</td><td width='12%' align='center' bgcolor='#FFFFEE'>");
        buf.append( purchaseOrderForm.getPOTypeString());
        buf.append("</td><td width='12%' align='center' bgcolor='#FFFFEE'>");
        buf.append( purchaseOrderForm.getPoDate()+"&nbsp;");
        buf.append("</td><td width='12%' align='center' bgcolor='#FFFFEE'>");
        buf.append( purchaseOrderForm.getVendorName()+"&nbsp;</td>");
        buf.append("<td width='12%' align='center' bgcolor='#FFFFEE'>");
        buf.append( purchaseOrderForm.getVendorQuoteNumber()+"&nbsp;</td>");
        buf.append("<td width='12%' align='center' bgcolor='#FFFFEE'>");
        buf.append( purchaseOrderForm.getPoMaxAmt()+"&nbsp;</td>");
        buf.append("<td width='14%' align='center' bgcolor='#FFFFEE'>");
        buf.append( purchaseOrderForm.getValidFromDate()+"&nbsp;</td>");
        buf.append("<td width='14%' align='center' bgcolor='#FFFFEE'>");
        buf.append( purchaseOrderForm.getValidToDate()+"&nbsp;</td>");
        buf.append("</tr>");
        buf.append ( "<tr>" );
        buf.append ( "<td width='12%' colspan='4' align='center' bgcolor='#DEE1E2' class='NArialR'>Shipping Method</td>" );
        buf.append ( "<td width='12%' colspan='4' align='center' bgcolor='#DEE1E2' class='NArialR'>Pay Terms</td>" );
        buf.append ( "</tr>" );
        buf.append ( "<tr>" );
        buf.append("<td width='12%' colspan='4' align='center' bgcolor='#FFFFEE'>");
        buf.append( purchaseOrderForm.getShipMethod() );
        buf.append("</td><td width='12%' colspan='4' align='center' bgcolor='#FFFFEE'>");
        buf.append( purchaseOrderForm.getPayTerms() );
        buf.append ( "</tr>" );
        buf.append ( "</table></td></tr>");
        buf.append("<tr><td colspan=4><img src=http://" + host + "/"+ ConfigManager.getChipTracContext ()  +"/jsp/includes/images/spacer.gif' height=10></td></tr>");
	    buf.append("<tr><td colspan=4><font class='NArialR'><strong><u>Comments: </u></strong></font></td></tr>");
        buf.append("<tr><td colspan=4 bgcolor='#DEE1E2' width='100%'><font class='NArialRS'>");
        buf.append( purchaseOrderForm.getCommentsForHTML());
        buf.append("&nbsp;</font></td></tr> <tr><td colspan=4>");
        buf.append("<img src='http://" + host + "/"+ ConfigManager.getChipTracContext ()  +"/jsp/includes/images/spacer.gif' height=10></td></tr>");
        buf.append("<tr><td colspan=4><img src='http://" + host + "/"+ ConfigManager.getChipTracContext ()  +"/jsp/includes/images/spacer.gif' height=20></td></tr>");
        buf.append("</table></form></body></html>");
        return buf.toString();
    }

}


